package com.fate.securecheckplatform;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.fate.securecheckplatform.base.BaseActivity;
import com.fate.securecheckplatform.bean.TableForbiddenType;
import com.fate.securecheckplatform.bean.TerminalInfoEntity;
import com.fate.securecheckplatform.bean.UserEntity;
import com.fate.securecheckplatform.constant.Constant;
import com.fate.securecheckplatform.db.DataBase;
import com.fate.securecheckplatform.net.MyObserver;
import com.fate.securecheckplatform.net.RequestUtils;
import com.fate.securecheckplatform.utils.DeviceIdUtil;
import com.fate.securecheckplatform.utils.ExecutorManager;
import com.fate.securecheckplatform.utils.LogUtil;
import com.fate.securecheckplatform.utils.SpUtil;
import com.fate.securecheckplatform.utils.ToastUtil;
import com.fate.securecheckplatform.utils.Util;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_account)
    EditText mEtAccount;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.iv_clear)
    ImageView mIvClear;
    @BindView(R.id.iv_hide_show)
    ImageView mIvHideShow;
    @BindView(R.id.tv_sbid)
    TextView mTvSbid;

    boolean isShowPassword = false;
    private String account = "";
    private String password = "";
    private RxPermissions rxPermissions;
    private DataBase dataBase;

    @Override
    protected int layoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {

        obtainUsersFromServer();
        obtainThingsType();
        obtainClientInfo();
    }

    /**
     * 获取设备信息
     */
    private void obtainClientInfo() {
        String deviceId = DeviceIdUtil.getLocalMacAddressFromIp();
        if (deviceId != "") {
            mTvSbid.setText("设备ID：" + deviceId);
        } else {
            mTvSbid.setText("设备ID获取失败");
        }
//        String deviceId = DeviceIdUtil.getDeviceId(this);
        RequestUtils.getTerminalInfos(this, deviceId,
                new MyObserver<List<TerminalInfoEntity>>(this) {
                    @Override
                    public void onSuccess(List<TerminalInfoEntity> result) {

                        if (result == null || result.size() == 0) return;
                        Log.e("--->", "obtainClientInfo :" + result.size());
                        Log.e("--->", "obtainClientInfo :" + result.get(0).toString());
                        SpUtil.getInstance().putString(Constant.SBMC, result.get(0).getSbmc());
                        SpUtil.getInstance().putString(Constant.SSWZ, result.get(0).getSswz());
                        insertClientToDB(result);
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {

                    }
                });
    }

    /**
     * 数据库插入
     *
     * @param result
     */
    private void insertClientToDB(List<TerminalInfoEntity> result) {
        ExecutorManager.getService().submit(() -> {
            dataBase.terminalDao().insertTerminals(result);
        });
    }

    private void obtainThingsType() {
        RequestUtils.getThingsType(this, new MyObserver<List<TableForbiddenType>>(this) {
            @Override
            public void onSuccess(List<TableForbiddenType> result) {
                Log.e("--->", "obtainThingsType :" + result.size());
                if (result != null && result.size() > 0) {
                    insertThingsTypeToDB(result);
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {

            }
        });
    }

    /**
     * 数据库中插入违禁物品类型
     *
     * @param result
     */
    private void insertThingsTypeToDB(List<TableForbiddenType> result) {

        ExecutorManager.getService().execute(() -> {
            dataBase.forbiddenTypeDao().deleteAllType();
            dataBase.forbiddenTypeDao().addTypes(result);
        });
    }

    /**
     * 从服务器获取信息
     */
    private void obtainUsersFromServer() {
        RequestUtils.getAllUser(this, new MyObserver<List<UserEntity>>(this) {
            @Override
            public void onSuccess(List<UserEntity> result) {
                Log.e("--->", "obtainUsersFromServer :" + result.size());
                if (result != null && result.size() > 0) {
                    insertUsers(result);
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtil.toast("" + errorMsg);
                Log.e("--->", "--" + errorMsg);
            }
        });
    }

    /**
     * 数据库中插入数据
     *
     * @param result
     */
    private void insertUsers(List<UserEntity> result) {
        ExecutorManager.getService().submit(() -> {
            dataBase.userDao().deleteAllUsers();
            dataBase.userDao().addUsers(result);
        });
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initView() {
        dataBase = DataBase.getInstance(this);
        mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CAMERA)
                .subscribe(aBoolean -> {
                    if (!aBoolean) {
                        System.exit(0);
                    }
                });

        String localName = SpUtil.getInstance().getString(Constant.LOGIN_NAME);
        LogUtil.e("-->", "Login-->" + localName);
        if (!TextUtils.isEmpty(localName)) {
            gotoNextPage();
        }

    }

    @OnClick({R.id.iv_clear, R.id.iv_hide_show, R.id.btn_login})
    public void onClickEvent(View v) {
        switch (v.getId()) {
            case R.id.iv_clear:
                mEtAccount.setText("");
                account = "";
                break;
            case R.id.iv_hide_show:
                isShowPassword = !isShowPassword;
                if (isShowPassword) {
                    mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            case R.id.btn_login:
                if (checkParams()) {
                    if (equalstoDataBase()) {
                        SpUtil.getInstance().putString(Constant.LOGIN_NAME, account);
                        gotoNextPage();
                    }
                }
                break;
        }
    }

    private boolean equalstoDataBase() {

        Future<UserEntity> future = ExecutorManager.getService().submit(() -> dataBase.userDao().getUserByAccount(account));
        if (future == null) {
            ToastUtil.toast("账号不存在");
            return false;
        }

        String mm;
        UserEntity entity;
        try {
            entity = future.get();
            if (entity != null) {
                mm = entity.getMm();
                LogUtil.e("-->", "--" + entity.getZzjgmc());
                LogUtil.e("-->", "--" + Util.getTeamNum(entity.getZzjgmc()));
                SpUtil.getInstance().putString(Constant.ZZJGMC, Util.getTeamNum(entity.getZzjgmc()));
            } else {
                ToastUtil.toast("账号不存在");
                return false;
            }
        } catch (ExecutionException e) {
            e.printStackTrace();
            ToastUtil.toast("未知错误");
            return false;
        } catch (InterruptedException e) {
            e.printStackTrace();
            ToastUtil.toast("未知错误");
            return false;
        }

        if (TextUtils.equals(Util.md5(password), mm)) {
            return true;
        } else {
            ToastUtil.toast("输入密码错误");
        }


        return false;
    }

    private void gotoNextPage() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    private boolean checkParams() {
        account = mEtAccount.getText().toString().trim();
        password = mEtPassword.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            ToastUtil.toast("请输入账号");
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtil.toast("请输入密码");
            return false;
        }
        return true;
    }

}
